package tgc.edu.yzy.custom;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class BackEndHttpRequest {
	//public static final String API = " eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6ImE0MzhlZmZlLTA0MzgtNGZjMy1iOTRhLTA0OTE2Njk0YzM3MSIsImlhdCI6MTU2NTI3MTQ0NCwic3ViIjoiZGV2ZWxvcGVyLzIxZGYzZTJmLWNiNWQtNGM2ZC04ZDMxLWFhNDMzMzlkODgxMyIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjQ3LjEwMS4xMjguMjAxIl0sInR5cGUiOiJjbGllbnQifV19.2T1XrsOMM2vM3UCYVP2PUHfpcGdZ4oEQKOnCeeg8KwNRMhtsuZLU4_WBH9tIb_838bDUFhPdmb_xjuTiHfwP7g";
	public static String API = " eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjgxMTA4M2UyLTMyOTctNDYxZC04NDRhLWI3MTkwMWU1ZmQ5OSIsImlhdCI6MTU2OTAzNjA1MSwic3ViIjoiZGV2ZWxvcGVyLzIxZGYzZTJmLWNiNWQtNGM2ZC04ZDMxLWFhNDMzMzlkODgxMyIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjQ3Ljk0LjEzNS4xNDgiXSwidHlwZSI6ImNsaWVudCJ9XX0.1UNzV44Anxo7WP3rWsqBZceMiPS1GfiW-to2wR-4PpkxpV8uljmh14aEBG-MKuKc5ThlD5b7UHcQfuIf-gbPBQ";
	public static CacheMap<String,String> cachemap = new CacheMap<>();
	
	private static String[] ips = {"47.94.135.148:8880","47.94.135.148:8853","121.36.96.4:8880","121.36.96.4:8853"};
	private static Integer sum = 0;
	private static String update(String url) {
		//String sendGetCoc = BackEndHttpRequest.sendGet("http://47.100.197.180:8855/coctest","tag="+tag);
		try {
			url = "http://"+ips[sum]+"/coc?url="+URLEncoder.encode(url + "", "UTF-8");
			sum++;
			if(sum==4) {
				sum = 0;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	/***
	 * 专门用于coc请求
	 * @param url
	 * @return
	 */
	public static String sendGetCoc(String url) {
		String string = cachemap.get(url);
		if(string!=null) {
			System.out.println("调取缓存:"+url);
			return string;
		}
		System.out.println(url);
		String result = "";
		//url = update(url); 
        BufferedReader bufferedReader = null;
        try {
            //1、读取初始URL
            String urlNameString = url;
            //2、将url转变为URL类对象
            URL realUrl = new URL(urlNameString);
            
            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
           
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("authorization", "Bearer"+API);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            //清除相应缓存
            connection.setDoOutput(true); 
            connection.setUseCaches(false);
            //5、建立实际的连接 
            connection.connect();
            //获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            //遍历所有的响应头字段
            String returns = map.get(null).get(0);
            if(returns.indexOf("200")!=-1) {
            	//6、定义BufferedReader输入流来读取URL的响应内容 ，UTF-8是后续自己加的设置编码格式，也可以去掉这个参数
            	bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
                String line = "";
                while(null != (line = bufferedReader.readLine())) {
                    result += line;
                }
                if(url.indexOf("players")!=-1) {
               	 cachemap.putPlusMinutes(url, result, 20);
               }else {
               	 cachemap.putPlusMinutes(url, result, 1);
               }
            }else if(returns.indexOf("400")!=-1) {
            	result = "400";
            	System.out.println("无法获取数据，提供的参数错误！400"+url);
            }else if(returns.indexOf("403")!=-1) {
            	result = "403";
            	System.out.println("无法访问，因为COCAPI出现问题！403"+url);
            }else if(returns.indexOf("404")!=-1) {
            	result = "404";
            	System.out.println("无法获取数据，数据丢失！404"+url);
            }else if(returns.indexOf("429")!=-1) {
            	result = "429";
            	System.out.println("无法获取数据，COCAPI已被截流限制！429"+url);
            }else if(returns.indexOf("500")!=-1) {
            	result = "500";
            	System.out.println("服务器请求异常！500"+url);
            }else if(returns.indexOf("503")!=-1) {
            	result = "503";
            	System.out.println("服务器维护！无法查询"+url);
            }else {
            	result = "200";
            	System.out.println("此次请求无法判断"+returns);
            }
        }catch (Exception e) {
        	result = "500";
            System.out.println("发送GETCOC请求出现异常！！！"+url);
            System.out.println(result);
        }finally {        //使用finally块来关闭输入流 
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return result;
	}
	
	/**
	 * 向指定的URL发送GET方法的请求
	 * 目前主要用在访问自己内网的服务器
     * @param url    发送请求的URL
     * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式 
     * @return       远程资源的响应结果 
     */
    public static String sendGet(String url, String param) {
    	System.out.println(url);
        String result = "";
        BufferedReader bufferedReader = null;
        try {
            //1、读取初始URL
            String urlNameString = url + "?" + param;
            //2、将url转变为URL类对象
            URL realUrl = new URL(urlNameString);
            
            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
           
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0");
            //connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            //清除相应缓存
            connection.setDoOutput(true); 
            connection.setUseCaches(false);
            //5、建立实际的连接 
            connection.connect();
            //获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            //遍历所有的响应头字段
            /*String n = "";
            for(String key : map.keySet()) {
                System.out.println(key + "---->" + map.get(key));
            }
            System.out.println(n);
            List<String> list = map.get(null);
            for (String string : list) {
				System.out.println(string);
			}*/
            String list = map.get(null).get(0);
            if(list.indexOf("200")!=-1) {
            	//6、定义BufferedReader输入流来读取URL的响应内容 ，UTF-8是后续自己加的设置编码格式，也可以去掉这个参数
            	bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            	String line = "";
            	while(null != (line = bufferedReader.readLine())) {
            		result += line;
            	}
            }
//            int tmp;
//            while((tmp = bufferedReader.read()) != -1){
//                result += (char)tmp;
//            }
            
        }catch (Exception e) {
            System.out.println("发送GET请求出现异常！！！");
            //e.printStackTrace();
        }finally {        //使用finally块来关闭输入流 
            try {
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 诸氏还是图灵机器人再用
     * 向指定的URL发送POST方法的请求
     * @param url    发送请求的URL
     * @param param  请求参数，请求参数应该是 name1=value1&name2=value2 的形式 
     * @return       远程资源的响应结果 
     */
    public static String sendPost(String url, Object param) {
        String result = "";
        BufferedReader bufferedReader = null;
        PrintWriter out = null;
        try {
            //1、2、读取并将url转变为URL类对象
            URL realUrl = new URL(url);
            
            //3、打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            //4、设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        
            // 发送POST请求必须设置如下两行  
            connection.setDoInput(true);
            connection.setDoOutput(true);
            
            //5、建立实际的连接
            //connection.connect();
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            //发送请求参数
            out.print(param);
            //flush输出流的缓冲
            out.flush();
            //
            //6、定义BufferedReader输入流来读取URL的响应内容
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line;
            while(null != (line = bufferedReader.readLine())) {
                result += line;
            }
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("发送POST请求出现异常！！！"  + e);
            e.printStackTrace();
        }finally {        //使用finally块来关闭输出流、输入流 
            try {
                if(null != out) {
                    out.close();
                }
                if(null != bufferedReader) {
                    bufferedReader.close();
                }
            }catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    /***
     * 主要是邮箱的请求再用
     * @param strUrl
     * @param params
     * @param method
     * @return
     * @throws Exception
     */
    public static String sendEmsGet(String strUrl, Map<String, String> params,String method) throws Exception  {
    	System.out.println(strUrl);
    	HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
    
    public static String urlencode(Map<String, String> params) {
    	
		StringBuilder sb = new StringBuilder();
        for (Map.Entry i : params.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
	}
    /***
     * 获取网络图片
     * @param url 
     * @param file
     * @throws Exception
     */
    public static void sendImageGet(String gourl,File file) throws Exception {
    	System.out.println(gourl);
    	
        
    	//new一个URL对象 
    	  URL url = new URL(gourl); 
    	  //打开链接 
    	  URLConnection conn = url.openConnection();
    	  //设置请求方式为"GET" 
    	  ((HttpURLConnection) conn).setRequestMethod("GET");
    	  conn.setRequestProperty("authorization", "Bearer"+API);
    	  conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    	  conn.setRequestProperty("connection", "Keep-Alive");
    	  conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    	//清除相应缓存
    	  conn.setDoOutput(true); 
    	  conn.setUseCaches(false);
    	  conn.connect();
    	  //通过输入流获取图片数据 
    	  InputStream inStream = conn.getInputStream(); 
    	  //得到图片的二进制数据，以二进制封装得到数据，具有通用性 
    	  byte[] data = readInputStream(inStream); 
    	  //new一个文件对象用来保存图片，默认保存当前工程根目录 
    	  //创建输出流 
    	  FileOutputStream outStream = new FileOutputStream(file); 
    	  //写入数据 
    	  outStream.write(data); 
    	  //关闭输出流 
    	  outStream.close(); 
    }
	private static byte[] readInputStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 
		  //创建一个Buffer字符串 
		  byte[] buffer = new byte[1024]; 
		  //每次读取的字符串长度，如果为-1，代表全部读取完毕 
		  int len = 0; 
		  //使用一个输入流从buffer里把数据读取出来 
		  while( (len=inStream.read(buffer)) != -1 ){ 
		   //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度 
		   outStream.write(buffer, 0, len); 
		  } 
		  //关闭输入流 
		  inStream.close(); 
		  //把outStream里的数据写入内存 
		  return outStream.toByteArray(); 
	}
	
	public static String getURL(String requestUrl,Map<String,Object> data,String method) throws IOException{
        HttpURLConnection conn = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String content = null;
        //GET请求的url链接
        if(null == method || "GET" == method){
            requestUrl = requestUrl+"?"+urlEncode(data);
        }
        
        try {
            
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            
            //设置请求方式
            if("GET" == method || null == method){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                //使用URL连接输出
                conn.setDoOutput(true);
            }
            //设置请求内核
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
            conn.setRequestProperty("Cookie","_ga=GA1.2.1599053079.1569457387; _gid=GA1.2.2047943731.1569457387; _gat=1");
            //设置不使用缓存
            conn.setUseCaches(false);
            //设置链接超时时间,毫秒为单位
            conn.setConnectTimeout(20000);
            //设置读取超时时间，毫秒为单位
            conn.setReadTimeout(20000);
            //设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
            conn.setInstanceFollowRedirects(false);
            //开启链接
            conn.connect();
            //处理post请求时的参数
            if(null != data && "POST" == method){
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.writeBytes(urlEncode(data));
            }
            //获取字符输入流
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String strContent = null;
            while((strContent = br.readLine()) != null){
                sb.append(strContent);
            }
            content = sb.toString();
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }finally{
            //关闭流和链接
            if(null != br){
                br.close();
            }
            if(null != conn){
                conn.disconnect();
            }
        }
        
        return content;
    }
       
    //将map型转为请求参数型
    public static String urlEncode(Map<String, ?> data) {
        if(data == null){
            return "";
        }else{
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, ?> i : data.entrySet()) {
                try {
                    sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    }
}
